package com.leyou.order.interceptor;

import com.leyou.common.auth.entity.UserHolder;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 当前拦截器的作用是：
 * 在进入处理器之前，获取到request域中的用户id，并存储起来，供处理器或者service使用
 */
public class UserInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("USER_ID");
        if(StringUtils.isBlank(userId)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        UserHolder.setUserId(userId);
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserHolder.removeUserId();
    }

}
